<!--
 * @Description: 
 * @Author: zhanyinjia
 * @Date: 2023-05-19 14:43:38
 * @LastEditors: zhanyinjia
 * @LastEditTime: 2023-05-23 10:42:57
-->
<template>
  <div>
    <div>
      <el-table
        max-height="500"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        show-summary
        row-key="idCode"
        :row-class-name="rowClassFn"
        @select="selectItem"
        @select-all="selectAll"
        :span-method="objectSpanMethod"
        :summary-method="getSummaries"
      >
        <el-table-column :reserve-selection="true" type="selection" prop="orderId" width="60"> </el-table-column>
        <el-table-column prop="orderId" label="orderId" width="80"></el-table-column>
        <el-table-column prop="orderNo" label="订单号" width="120"></el-table-column>
        <el-table-column prop="materialCode" label="物料编码" width="120"> </el-table-column>
        <el-table-column prop="materialName" label="物料名称" width="120"> </el-table-column>
        <el-table-column prop="price" label="单价" width="120"> </el-table-column>
        <el-table-column prop="taxRate" label="税率" width="120"> </el-table-column>
        <el-table-column prop="num" label="数量" width="120"> </el-table-column>
        <el-table-column prop="amount" label="金额"> </el-table-column>
      </el-table>
      <pagination :pageNum="pagenum" :pageSize="5" :total="total" @goSpecifiedPage="pageChange"></pagination>
      <p>
        <strong>本期对账总计：</strong>订单条目合计{{ checkSumary.orderSum }}，物料条目合计{{
          checkSumary.materialSum
        }}，数量合计{{ checkSumary.numSum }}，金额总计{{ checkSumary.amountSum }}
      </p>
      <p>
        <strong>已选物料[orderId-materialCode]：</strong>
        <span v-for="item in checkedData" :key="`${item.orderId}-${item.materialCode}`"
          >{{ item.orderId }}_{{ item.materialCode }}、</span
        >
      </p>
    </div>
  </div>
</template>

<script>
import { tableList, summationMap } from './config'
import { calculateMerges, nest2flat } from '@/utils/common'
export default {
  data() {
    return {
      pagenum: 1,
      total: 150,
      tableData: [],
      pageSumary: {
        numSum: 0,
        amountSum: 0
      },
      checkedData: [] //已选中项
    }
  },
  computed: {
    checkedIds() {
      //已选中项的id
      return this.checkedData.reduce((prev, next) => {
        prev.push({
          orderId: next.orderId
        })
        return prev
      }, [])
    },
    listMap() {
      //{orderId:[materialCode...]}
      return this.tableData.reduce((prev, next) => {
        const [id, code] = next.idCode.split('-')
        if (prev[id]) {
          prev[id].push(code)
        } else {
          prev[id] = [code]
        }
        return prev
      }, {})
    },
    checkSumary() {
      let orderSum = new Set([])
      const sumary = this.checkedData.reduce(
        (prev, next) => {
          orderSum.add(next.orderId)
          prev.materialSum += 1
          prev.numSum += next.num
          prev.amountSum += next.amount
          return prev
        },
        { materialSum: 0, numSum: 0, amountSum: 0 }
      )
      sumary.orderSum = orderSum.size
      return sumary
    }
  },
  created() {
    const { flatList, sumary } = this.handleCellMerge(tableList)
    this.tableData = flatList
    this.pageSumary = sumary
  },
  methods: {
    // 列表增加字段idCode，为orderId-materialCode拼接
    addExtroFiled(list) {
      return list.reduce((prev, next) => {
        next.idCode = `${next.orderId}-${next.materialCode}`
        prev.push(next)
        return prev
      }, [])
    },
    // 单元格合并
    objectSpanMethod({ row, column }) {
      const merge = `${column.property}-merge`
      if (row[merge]) {
        return row[merge]
      }
    },
    getSummaries(param) {
      const { columns } = param

      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[0] = '合计'
        } else if (index === 1) {
          sums[1] = `已选${this.checkSumary.orderSum}条`
        } else {
          sums[index] = summationMap[column.property] ? this.pageSumary[summationMap[column.property]] : ''
        }
      })
      return sums
    },
    rowClassFn({ row }) {
      //return 'select-hidden'
    },
    pageChange(num) {
      let list = []
      if (num == 1) {
        list = tableList
      } else {
        list = []
        for (let i = 1; i < 6; i++) {
          list.push({
            orderId: 5 * (num - 1) + i,
            orderNo: `HSD415${5 * (num - 1) + i}`,
            materialList: [
              { materialCode: 'DS45214', materialName: '枸杞', price: 100, num: 1, taxRate: 0.03, amount: 100 },
              { materialCode: 'DS45212', materialName: '党参', price: 50, num: 2, taxRate: 0.07, amount: 100 }
            ]
          })
        }
      }

      const { flatList, sumary } = this.handleCellMerge(list)
      this.tableData = flatList
      this.pageSumary = sumary
    },
    handleCellMerge(list) {
      const flatData = nest2flat(list, 'materialList')
      const mergesDeps = ['orderId']
      const mergeColumns = {
        0: ['orderId', 'orderNo']
      }
      const flatList = calculateMerges(flatData, {
        mergesDeps,
        mergeColumns
      })

      // flatList增加字段idCode，为orderId-materialCode拼接
      return flatList.reduce(
        (prev, next) => {
          next.idCode = `${next.orderId}-${next.materialCode}`
          prev.flatList.push(next)
          prev.sumary.numSum += next.num
          prev.sumary.amountSum += next.amount
          return prev
        },
        { flatList: [], sumary: { numSum: 0, amountSum: 0 } }
      )
    },
    // selection单选
    selectItem(selection, row) {
      console.log(selection)
      const result =
        selection.length &&
        selection.findIndex((v) => v.orderId == row.orderId && v.materialCode == row.materialCode) > -1
      this.listMap[row.orderId].forEach((item) => {
        if (item != row.materialCode) {
          const rowItem = this.tableData.find((v) => v.orderId == row.orderId && v.materialCode == item)
          console.log(rowItem)
          this.$refs.multipleTable.toggleRowSelection(rowItem, result)
        }
      })
      this.$nextTick(() => {
        this.calculate()
      })
    },
    // 全选
    selectAll() {
      this.calculate()
    },
    calculate() {
      this.checkedData = this.$refs.multipleTable.selection
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .select-hidden .el-checkbox {
  display: none !important;
}
</style>